package com.hxzy.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.common.util.ServletUtil;
import com.hxzy.common.vo.CodeEnum;
import com.hxzy.common.vo.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败或没有权限 (默认输出  403状态码)
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        if(authException instanceof InsufficientAuthenticationException){
            ServletUtil.renderString(response,  JSONObject.toJSONString(R.failed(CodeEnum.TOKEN_INVALIDATE)));
            return;
        }

        String msg =  "请求访问："+request.getRequestURI()+"，认证失败，无法访问系统资源";
        ServletUtil.renderString(response, JSONObject.toJSONString(R.failed(msg)));
    }
}
